package org.yanghe.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class CCircleBreakerController {

    @Value("${service-url.nacos-provider-service}")
    private String url;

    @Resource
    private RestTemplate restTemplate;
    //1.FallBack 只负责业务异常
    //@SentinelResource(value = "fallback",fallback = "handlerFallBack")
    //2.blockHandler 只负责 sentinel 控制台配置违规
    //@SentinelResource(value = "fallback",blockHandler = "blockHandler")
    //3.两者都配置  fallBack 负责程序异常，blockHandler负责 sentinel 控制台异常
    //当两者异常都有的话 只会进入 blockHandler 异常处理
    @SentinelResource(value = "fallback"
            ,fallback = "handlerFallBack"
            ,blockHandler = "blockHandler"
            ,exceptionsToIgnore = {IllegalArgumentException.class})//假如出现该异常，fallBack兜底，不没有降级效果
    @GetMapping(value = "/consumer/fallback/{id}")
    public String testRestTemplate(@PathVariable("id") Integer id){
        String result = restTemplate.getForObject(url + "/provider/fallback/" + id, String.class);
        if(id==4){
            throw new IllegalArgumentException("IllegalArgumentException,非法参数异常....");
        }else if(result==null){
            throw new NullPointerException("NullPointerException,该id没有对应记录，空指针异常");
        }
        return "Consumer 远程调用 --> "+result;
    }

    /**
     * 本例是 fallback
     * @param id
     * @return
     */
    public String handlerFallBack(@PathVariable("id") Integer id, Throwable e){
        return "系统异常，Consumer 进行服务降级处理 handlerFallBack: "+e.getMessage();
    }

    /**
     * 本例是 blockHandler
     * @param id
     * @return
     */
    public String blockHandler(@PathVariable("id") Integer id, BlockException e){
        return "系统异常，Consumer 进行服务降级处理 BlockException : "+e.getMessage();
    }

}
